# coding:utf-8
# !/usr/bin/python3
from config.settings import DB_SERVER
import pymysql


class MysqlConnection:
    def __init__(self, host=None, port=None, username=None, password=None, db_name=None):
        if not host:
            self.host = DB_SERVER
            # self.host = 'localhost'
        else:
            self.host = host
        if not port:
            self.port = 3307
        else:
            self.port = port
        if not username:
            self.username = 'root'
        else:
            self.username = username
        if not password:
            self.password = 'root'
        else:
            self.password = password
        if not db_name:
            self.db_name = 'scide'
        else:
            self.db_name = db_name

        self.conn = self.connectToDB()

        self.cursor = self.conn.cursor()

    def connectToDB(self):
        conn = pymysql.connect(host=self.host,
                               port=self.port,
                               user=self.username,
                               password=self.password,
                               database=self.db_name, charset='utf8')
        # 使用 cursor() 方法创建一个游标对象 cursor
        return conn

    def execute_sql(self, sql=None):
        if not sql:
            return False
        else:
            result = self.cursor.execute(sql)

            return result > 0

    def disconnectToDB(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

    def __enter__(self):
        # code to start a new transaction
        cursor = self.cursor
        return cursor

    def __exit__(self, exe_type, exe_value, exe_traceback):
        if exe_traceback is None:
            # No execption, so commit
            self.conn.commit()
            self.disconnectToDB()
            return True
        else:
            # Exception occurred, so rollback
            self.conn.rollback()
            self.disconnectToDB()
            return False


if __name__ == "__main__":
    with MysqlConnection() as cursor:
        cursor.execute('select * from file_upload_record limit 10')
        result = cursor.fetchall()
        for item in result:
            print(item)



